package com.alibaba.otter.node.etl.load.loader.mq.rabbit.serializer;

import com.alibaba.otter.node.etl.load.loader.mq.rabbit.exception.MqSerializeException;
import com.alibaba.otter.node.etl.load.loader.mq.rabbit.model.MessageContext;
import com.alibaba.otter.node.etl.load.loader.mq.rabbit.provider.SerializerProvider;
import com.alibaba.otter.node.etl.load.loader.mq.rabbit.provider.TargetClassExplorer;
import com.rabbitmq.client.AMQP;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SerializeUtils {

    public static Object deserializeMessage(MessageContext context,
                                            SerializerProvider serializerProvider,
                                            TargetClassExplorer classExplorer) {

        Serializer serializer = null;
        Class<?> targetClass = null;
        try {
            AMQP.BasicProperties properties = (AMQP.BasicProperties) context.getMessage().getProperty();
            targetClass = classExplorer.explore(properties);
            serializer = serializerProvider.provide(properties, targetClass);
            return serializer.deserialize(context.getMessage().getContent(), targetClass);
        } catch (MqSerializeException e) {
            String targetClzName = targetClass == null ? "null" : targetClass.getName();
            log.error(e.getMessage() + ", targetClass: " + targetClzName + ", serializer" + serializer, e);
            throw e;
        } catch (Exception e) {
            String targetClzName = targetClass == null ? "null" : targetClass.getName();
            log.error("反序列化失败, targetClass: " + targetClzName + ", serializer" + serializer, e);
            throw new MqSerializeException("反序列化失败", targetClass, serializer, e);
        }
    }
}
